<template>
  <div class="approval">
    <el-card class="box-card" style="margin-top: 110px;">
      <div class="title">{{$t('achievements.title1')}}</div>
      <div class="menu-search">
        <div class="menu-title">
          <!-- 组名称 -->
          <div class="searchItem">
            <span>{{$t('userGroupManager.gropuName')}}</span>
            <el-input
              v-model="listQuery.groupName"
              size="small"
              :placeholder="$t('userGroupManager.ruleGropuName')"
            ></el-input>
          </div>
          <!-- 组类型 -->
          <div class="searchItem">
            <span>{{$t('group.groupType')}}</span>
            <el-select v-model="listQuery.groupType" :placeholder="$t('rule.all')" size="small">
              <el-option
                v-for="item in roleType"
                :key="item.id"
                :label="item.dictValue"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
          <!-- 渠道 -->
          <div class="searchItem">
            <span>{{$t('productManage.channels')}}</span>
            <div class="tree-select">
              <treeselect
                v-model="listQuery.channels"
                :placeholder="$t('rule.all')"
                :multiple="true"
                :options="channelArr"
                :openOnFocus="true"
                :show-count="true"
                :default-expand-level="1"
              />
            </div>
          </div>
        </div>
        <div class="menu-title-btn">
          <button type="button" @click="search">{{$t('btn.query')}}</button>
          <button type="button" @click="reset">{{$t('btn.reset')}}</button>
        </div>
      </div>
    </el-card>
    <el-card class="box-card" style="margin-top: 10px;margin-bottom: 20px;">
      <div style="display: flex; justify-content: space-between;">
        <div class="title">{{$t('DailyStatistics.ListDetails')}}</div>
        <div>
          <!-- 添加组 -->
          <el-button
            type="primary"
            size="small"
            @click="handleCreate"
            v-if="userGroupManager_add_group"
          >{{$t('userGroupManager.addGroup')}}</el-button>
        </div>
      </div>
      <el-table
        v-loading.body="listLoading"
        border
        stripe
        :data="tableData"
        style="width: 100%; margin-top: 5px;"
      >
        <el-table-column header-align="center" align="center" width="65" :label="$t('user.num')">
          <template slot-scope="scope">
            <span>{{scope.row.index}}</span>
          </template>
        </el-table-column>
        <!-- 组名称 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="name"
          :label="$t('userGroupManager.gropuName')"
          width="200"
        ></el-table-column>
        <!-- 组类型 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="userGroupType"
          :label="$t('group.groupType')"
          width="200"
        ></el-table-column>
        <!-- 渠道 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="orgName"
          :label="$t('productManage.channels')"
          width="200"
        ></el-table-column>
        <!-- 组描述 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="description"
          :label="$t('userGroupManager.groupDesc')"
          width="400"
        ></el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          :label="$t('user.operation')"
          width="150"
          fixed="right"
        >
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              size="small"
              type="text"
              @click="handleUpdate(scope.row)"
              v-if="userGroupManager_edit_group"
            >{{$t('btn.edit')}}</el-button>
            <!-- 删除 -->
            <el-button
              size="small"
              type="text"
              style="color: #f56c6c;"
              @click="handleDelete(scope.row)"
              v-if="userGroupManager_delete_group"
            >{{$t('btn.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogSendFormVisible"
      :before-close="closeDialog"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" style="width: 92%;" label-position="left">
        <!-- 组名称 -->
        <el-form-item :label="$t('userGroupManager.gropuName')" prop="name">
          <el-input
            size="small"
            v-model="form.name"
            :placeholder="$t('userGroupManager.inpGroupName')"
          ></el-input>
        </el-form-item>
        <!-- 组类型 -->
        <el-form-item :label="$t('group.groupType')" prop="attr1">
          <el-select size="small" v-model.number="form.attr1" :placeholder="$t('rule.choose')" @change="changeType(form.attr1)" style="width: 100%;">
            <el-option
              v-for="item in roleType"
              :key="item.dictCode"
              :label="item.dictValue"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 催收阶段 -->
        <div style="display: flex;" v-if="showStage">
          <el-form-item :label="$t('userGroupManager.collStage')" prop="startDay">
            <el-input
              size="small"
              v-model="form.startDay"
              :placeholder="$t('productManage.startDay')"
              style="width: 80px;"
            ></el-input>
          </el-form-item>
          <div style="width: 20px;height: 30px;line-height: 30px;text-align: center;">-</div>
          <el-form-item label prop="endDay" label-width="0">
            <el-input
              size="small"
              v-model="form.endDay"
              :placeholder="$t('productManage.endDay')"
              style="width: 80px;"
            ></el-input>
          </el-form-item>
        </div>
        <!-- 渠道 -->
        <div class="trees">
          <el-form-item :label="$t('productManage.channels')" prop="attr2">
            <div class="tree-select groups">
              <treeselect
                v-model="form.attr2"
                :placeholder="$t('rule.choose')"
                :options="channelArr"
                :openOnFocus="true"
                :show-count="true"
                :default-expand-level="1"
              />
            </div>
          </el-form-item>
        </div>
        <!-- 组描述 -->
        <el-form-item :label="$t('userGroupManager.groupDesc')" prop="description">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5}"
            v-model="form.description"
            :placeholder="$t('rule.toLength')" 
            :maxlength="500"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="create('form')"
          :loading="isAddLoading"
        >{{$t('btn.conserve')}}</el-button>
        <el-button
          v-if="dialogStatus=='update'"
          type="primary"
          @click="update('form')"
          :loading="isUpdateLoading"
        >{{$t('btn.conserve')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getAllRoleTypes,
  getChannelTree,
  page,
  addGroup,
  updateGroup,
  deleteGroup
} from "api/admin/userGroupManager/index";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  data() {
    return {
      userGroupManager_add_group: false,
      userGroupManager_edit_group: false,
      userGroupManager_delete_group: false,
      dialogStatus: "",
      textMap: {
        create: this.$t("userGroupManager.addGroup"),
        update: this.$t("userGroupManager.editGroup")
      },
      listLoading: false,
      roleType: [],
      channelArr: [],
      form: {
        name: undefined,
        attr1: undefined,
        attr2: null,
        description: undefined,
        startDay: undefined,
        endDay: undefined
      },
      rules: {
        name: [
          {
            required: true,
            message: this.$t("userGroupManager.inpGroupName")
          }
        ],
        attr1: [
          {
            required: true,
            message: this.$t("userGroupManager.ruleGroupType")
          }
        ],
        attr2: [
          {
            required: true,
            message: this.$t("userGroupManager.ruleChannel")
          }
        ],
        startDay: [
          {
            required: true,
            message: this.$t("productManage.startDay")
          }
        ],
        endDay: [
          {
            required: true,
            message: this.$t("productManage.endDay")
          }
        ]
      },
      dialogSendFormVisible: false,
      dialogEditFormVisible: false,
      total: null,
      expDis: true,
      listQuery: {
        limit: 10,
        page: 1,
        groupName: "",
        groupType: "",
        channels: null
      },
      tableData: [],
      currentId: "",
      showStage: false,
      isAddLoading: false,
      isUpdateLoading: false
    };
  },
  computed: {
    ...mapGetters(["elements"])
  },
  created() {
    this.userGroupManager_add_group = this.elements['userGroupManager:add_group'];
    this.userGroupManager_edit_group = this.elements['userGroupManager:edit_group'];
    this.userGroupManager_delete_group = this.elements['userGroupManager:delete_group'];
    // 组类型
    this.roleTypes();
    // 渠道
    this.getChannel();
    this.getList();
  },
  methods: {
    // 组类型下拉
    roleTypes() {
      getAllRoleTypes().then(res => {
        this.roleType = res;
      });
    },
    // 渠道下拉
    getChannel() {
      getChannelTree().then(res => {
        this.channelArr = res;
      });
    },
    // 修改组类型
    changeType(val) {
      if (val !== undefined || val !== '' || val !== null) {
        if (val === 'collect') {
          this.showStage = true;
        } else {
          this.showStage = false;
        }
      } else {
        this.form.attr1 = null;
      }
    },
    closeDialog(done) {
      done();
      this.$refs["form"].resetFields();
      this.getList();
    },
    resetTemp() {
      this.form = {
        name: undefined,
        attr1: undefined,
        attr2: null,
        description: undefined,
        startDay: undefined,
        endDay: undefined
      };
    },
    // 点击添加按钮
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogSendFormVisible = true;
      this.isAddLoading = false;
    },
    // 添加保存按钮
    create(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.$confirm(this.$t("loanDetail.cue1"), this.$t("user.cue2"), {
            confirmButtonText: this.$t("btn.confirm"),
            cancelButtonText: this.$t("btn.cancel"),
            type: "warning"
          }).then(() => {
            let obj = {};
            obj.name = this.form.name;
            obj.attr2 = this.form.attr2;
            obj.description = this.form.description;
            obj.startDay = this.form.startDay;
            obj.endDay = this.form.endDay;
            this.roleType.forEach(item => {
              if (this.form.attr1 === item.dictCode) {
                obj.attr1 = item.id;
                obj.code = item.dictCode;
              }
            })
            this.isAddLoading = true;
            addGroup(obj)
            .then((res) => {
              this.isAddLoading = false;
              if (res.status === 200) {
                this.dialogSendFormVisible = false;
                this.getList();
                this.$notify({
                  title: this.$t('user.success'),
                  message: this.$t('user.crtsuccess'),
                  type: 'success',
                  duration: 2000
                });
              }
            });
          }).catch(() => {
            this.isAddLoading = false;
            this.$message({
              showClose: true,
              type: "info",
              message: this.$t("orderQuery.cue2")
            });
          });
        } else {
          return false;
        }
      });
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.roleType.forEach(item => {
        if (Number(row.attr1) === item.id) {
          row.attr1 = item.dictCode;
        }
      })
      if (row.attr4 !== '') {
        this.showStage = true;
        row.attr4 = row.attr4.split(',');
        row.startDay = row.attr4[0];
        row.endDay = row.attr4[1];
      }
      this.form = Object.assign({}, row);
      this.currentId = row.id;
      this.dialogStatus = "update";
      this.dialogSendFormVisible = true;
      this.isUpdateLoading = false;
    },
    // 编辑保存按钮
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.$confirm(this.$t("loanDetail.cue1"), this.$t("user.cue2"), {
            confirmButtonText: this.$t("btn.confirm"),
            cancelButtonText: this.$t("btn.cancel"),
            type: "warning"
          }).then(() => {
            let obj = {};
            obj.id = this.currentId;
            obj.name = this.form.name;
            obj.startDay = this.form.startDay;
            obj.endDay = this.form.endDay;
            obj.attr2 = this.form.attr2;
            obj.description = this.form.description;
            this.roleType.forEach(item => {
              if (this.form.attr1 === item.dictCode) {
                obj.attr1 = item.id;
                obj.code = item.dictCode;
              }
            })
            this.isUpdateLoading = true;
            updateGroup(obj).then(() => {
              this.isUpdateLoading = false;
              this.dialogSendFormVisible = false;
              this.getList();
              this.$notify({
                title: this.$t('user.success'),
                message: this.$t('menu.uptsuccess'),
                type: 'success',
                duration: 2000
              });
            });
          }).catch(() => {
            this.isUpdateLoading = false;
            this.$message({
              showClose: true,
              type: "info",
              message: this.$t("orderQuery.cue2")
            });
          });
        } else {
          return false;
        }
      });
    },
    // 点击删除按钮
    handleDelete(row) {
      this.$confirm(this.$t("userGroupManager.delWarn"), this.$t("user.cue2"), {
        confirmButtonText: this.$t("btn.confirm"),
        cancelButtonText: this.$t("btn.cancel"),
        type: "warning"
      }).then(() => {
      let obj = {};
      obj.id = row.id;
      deleteGroup(obj)
        .then(() => {
          this.$notify({
            title: this.$t('user.success'),
            message: this.$t('user.delsuccess'),
            type: 'success',
            duration: 2000
          });
          this.getList();
        });
      }).catch(() => {
        this.$message({
          showClose: true,
          type: "info",
          message: this.$t("orderQuery.cue2")
        });
      });
    },
    getList() {
      if (this.listQuery.channels !== null) {
        if (this.listQuery.channels.length > 0) {
          this.listQuery.channels = this.listQuery.channels.join();
        } else {
          this.listQuery.channels = null;
        }
      }
      page(this.listQuery)
      .then(res => {
        if (res.status === 200) {
          this.listLoading = false;
          this.tableData = res.data.rows;
          this.tableData.forEach((item, index) => {
            item.index = index + (this.listQuery.page - 1) * this.listQuery.limit + 1
          })
          this.total = Number(res.data.total);
        } else {
          this.listLoading = true;
        }
      })
    },
    //查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    //重置
    reset() {
      this.listQuery.limit = 10;
      this.listQuery.page = 1;
      this.listQuery.groupName = "";
      this.listQuery.groupType = "";
      this.listQuery.channels = null;
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>
<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before {
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px 0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div:nth-child(2) {
      width: 200px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px 0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
      width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  margin-left: 20px;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.tree-select /deep/.vue-treeselect__control {
  padding-left: 5px;
  padding-right: 5px;
  display: table;
  table-layout: fixed;
  width: 100%;
  height: 30px!important;
  border: 1px solid #bfcbd9;
  border-radius: 5px;
  background: #fff;
  transition-duration: 200ms;
  transition-property: border-color, box-shadow, width, height, background-color,
    opacity;
  transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
}
.tree-select {
  width: 300px;
  height: 30px;
}
.tree-select
  /deep/.vue-treeselect--searchable:not(.vue-treeselect--disabled)
  .vue-treeselect__value-container {
  cursor: pointer;
}
.tree-select /deep/.vue-treeselect__menu-container {
  position: absolute;
  left: 0;
  width: 100%;
  overflow: visible;
  transition: 0s;
  max-height: 274px;
  z-index: 2000 !important;
}
.tree-select /deep/.vue-treeselect {
  position: absolute;
  text-align: left;
  width: 300px;
}
.tree-select /deep/.vue-treeselect__label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: table-cell;
    padding-left: 5px;
    max-width: 100%;
    vertical-align: middle;
    cursor: inherit;
    font-size: 12px;
    color: #5f5f61;
}
.tree-select /deep/.vue-treeselect__multi-value {
  max-height: 76px;
  overflow: auto;
}
.groups {
  width: 100%;
  height: 30px;
}
.groups /deep/.vue-treeselect {
  position: absolute;
  text-align: left;
  width: 100%;
  height: 30px;
}
.groups /deep/.vue-treeselect__menu-container {
  min-height: 30px;
}
.groups /deep/.vue-treeselect__multi-value {
  min-height: 30px;
  margin-bottom: 0;
}
.groups /deep/.vue-treeselect__multi-value-item {
  cursor: pointer;
  display: inline-table;
  background: #e3f2fd;
  padding: 0;
  border: 1px solid transparent;
  border-radius: 2px;
  color: #039be5;
  font-size: 12px;
  vertical-align: top;
}
.tree-select /deep/label {
  font-weight: normal!important;
}
.approval /deep/.vue-treeselect__control-arrow {
    width: 11px;
    height: 11px;
    color: #bfcbd9;
}
.approval /deep/.vue-treeselect__placeholder,
.vue-treeselect__single-value {
  color: #97a8be;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 5px;
  padding-right: 5px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  line-height: 30px !important;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  pointer-events: none;
}
</style>

